package hanlder

import (
	"art-list/cache"
	"art-list/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var user []models.Article
	rdis_key := "article_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, rdis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, rdis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	var total int64
	models.DB.Model(&models.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "ok",
		"data":  user,
		"total": total,
	})
	return
}
func List1(c *gin.Context) {
	id := c.Query("id")
	var user models.Article
	rdis_key := "article_list_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, rdis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, rdis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "ok",
		"data": user,
	})
	return
}
